package com.fengpanlong.web;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fengpanlong.entity.Employee;
import com.fengpanlong.entity.EmployeeProject;
import com.fengpanlong.entity.Project;
import com.fengpanlong.service.PagerService;
import com.fengpanlong.util.Pager;
import com.fengpanlong.util.StringUtil;


public class MainServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getMethod();
		String m = request.getParameter("_m");
		if("GET".equalsIgnoreCase(method)) {
			if("secureQuit".equals(m)) {
				secureQuit(request,response);
			} else {
				loadProject(request,response);
			}
		} else {
			
		}
	}
	/**
	 * 安全退出
	 * @param request
	 * @param response
	 */
	private void secureQuit(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		request.getSession().invalidate();
		goTojsp(request, response, "login.jsp");
	}
	/**
	 * 加载醒目列表
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void loadProject(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pageNum = request.getParameter("p");
		int num  = 1;
		
		if(StringUtil.isNotEmpty(pageNum)) {
			try {
				num = Integer.parseInt(pageNum);
			} catch (NumberFormatException e) {
				response.sendRedirect("main.jspx？p=1");
				return;
			}
		}
		Employee employee = (Employee)request.getSession().getAttribute("employee");
		EmployeeProject ep = new EmployeeProject();
		ep.setEmployee(employee);
		ep.setEmployeeId(employee.getId());
		request.getSession().setAttribute("ep", ep);
		Pager<Project> pager = PagerService.findPagerOfProjectsByEmployeeId(num, employee.getId());
		request.setAttribute("pager", pager);
		goTojsp(request, response, "main.jsp");
	}
	/**
	 * 去对应jsp页面
	 * @param request
	 * @param response
	 * @param jspName
	 * @throws ServletException
	 * @throws IOException
	 */
	private void goTojsp(HttpServletRequest request,
			HttpServletResponse response, String jspName) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/views/" + jspName).forward(request, response);
	}
}
